package com.biz.primus.ms.commodity.dao.redis.saleTag;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.base.enums.commodity.IStatus;
import com.biz.primus.ms.commodity.dao.ro.SaleTagRo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

/**
 * Created by aaa on 2017/6/5.
 */
@Repository
public class SaleTagBackendRedisDao extends CrudRedisDao<SaleTagRo, Long> implements Serializable{

    @Override
    public void save(SaleTagRo ro) {
        super.save(ro);
        String key = getNmaeMappingkey();
        zadd(key, ro.getUpdateTimestamp(), String.format("%s:%s", ro.getId(), ro.getTagName()));
        String normalKey = getNormalMappingKey();
        if(IStatus.NORMAL.equals(ro.getStatus())){
            zadd(normalKey, ro.getUpdateTimestamp(), ro.getId());
        }
    }

    private String getNormalMappingKey() {
        return getKeyByParams("normalIds");
    }

    private String getNmaeMappingkey() {
        return getKeyByParams("names");
    }

    @Override
    public void delete(SaleTagRo ro) {
        super.delete(ro);
        String key = getNmaeMappingkey();
        zrem(key, String.format("%s:%s", ro.getId(), ro.getTagName()));
    }

    public List<String> getNames(){
        String key = getNmaeMappingkey();
        final Set<byte[]> bytes = zRange(key, 0, -1);
        if(CollectionUtils.isNotEmpty(bytes)){
            return RedisUtil.bytesSetToStringList(bytes);
        }
        return Lists.newArrayList();
    }

    public List<SaleTagRo> getNorMalSaleTags(){
        final String key = this.getNormalMappingKey();
        final Set<byte[]> bytes = zRange(key, 0, -1);
        if(CollectionUtils.isNotEmpty(bytes)){
            final List<Long> ids = RedisUtil.bytesSetToLongList(bytes);
            return super.findByIds(ids);
        }
        return Lists.newArrayList();
    }
}
